/*
@Time : 2018/10/12 14:54
@Author : LiM
@File : CryptUtils
@Software: GoLand
*/
package crypt

import (
	. "MerelybG/Common/Calendar"
	"encoding/base64"
	"log"
	"strconv"
	"strings"
)

/**
base64加密
*/
func EncryptBase64(strSource string) string {
	btSource := []byte(strSource)
	return base64.StdEncoding.EncodeToString(btSource)
}

/**
base64解密
*/
func DecryptBase64(strSource string) string {
	btSource, err := base64.StdEncoding.DecodeString(strSource)
	if err != nil {
		log.Fatalln(err)
		return ""
	}
	return string(btSource)
}

/**
八字加密
*/
func Encrypt(strSource, strDate string) string {
	var strEtDate string = EncryptBase64(EightCharactersOfDate(strDate))
	var strEtSource string = EncryptBase64(strSource)
	var strNumDate string = strings.Replace(strDate, " ", "", -1)
	strNumDate = strings.Replace(strNumDate, "-", "", -1)
	strNumDate = strings.Replace(strNumDate, ":", "", -1)
	var runeEtDate = []rune(strEtDate)
	var runeEtSource = []rune(strEtSource)
	var runeNumDate = []rune(strNumDate)
	if (len(runeEtSource) > 10) && (len(runeEtDate) > 10) {
		for iIndex, iNum := range runeNumDate {
			iChageNum, err := strconv.Atoi(string(runeNumDate[iIndex]))
			if err != nil {
				return ""
			}
			if iChageNum > 0 {
				runeEtSource[iChageNum] = rune(int(runeEtSource[iChageNum]) + int(iNum))
			}
		}
		var iSourceLen int = len(runeEtSource) - 1

		for iIndex, iNum := range runeNumDate {
			iChageNum, err := strconv.Atoi(string(runeNumDate[iIndex]))
			if err != nil {
				return ""
			}
			if iChageNum > 0 {
				runeEtSource[iSourceLen-iChageNum] = rune(int(runeEtSource[iSourceLen-iChageNum]) + int(iNum))
			}
		}
	}

	return string(runeEtSource)
}

func Decrypt(strSource, strDate string) string {
	var strEtDate string = EncryptBase64(EightCharactersOfDate(strDate))
	var strNumDate string = strings.Replace(strDate, " ", "", -1)
	strNumDate = strings.Replace(strNumDate, "-", "", -1)
	strNumDate = strings.Replace(strNumDate, ":", "", -1)
	var runeEtDate = []rune(strEtDate)
	var runeEtSource = []rune(strSource)
	var runeNumDate = []rune(strNumDate)
	if (len(runeEtSource) > 10) && (len(runeEtDate) > 10) {
		var iNumDate int = len(runeNumDate)
		var iSourceLen int = len(runeEtSource) - 1
		for iIndex := iNumDate - 1; iIndex > -1; iIndex-- {
			iChageNum, err := strconv.Atoi(string(runeNumDate[iIndex]))
			if err != nil {
				return ""
			}
			if iChageNum > 0 {
				runeEtSource[iSourceLen-iChageNum] = rune(int(runeEtSource[iSourceLen-iChageNum]) - int(runeNumDate[iIndex]))
			}
		}

		for iIndex := iNumDate - 1; iIndex > -1; iIndex-- {
			iChageNum, err := strconv.Atoi(string(runeNumDate[iIndex]))
			if err != nil {
				return ""
			}
			if iChageNum > 0 {
				runeEtSource[iChageNum] = rune(int(runeEtSource[iChageNum]) - int(runeNumDate[iIndex]))
			}
		}

	}
	return DecryptBase64(string(runeEtSource))
}
